//
//  YiServerListView.swift
//  yiplayer
//
//  Created by wkun on 2024/6/13.
//

import SMBClient

enum ServerType: Int{
    case smb = 1
    case ftp = 2
    case webdav = 3
}

class YiServerListView : YiListView{
    
    static func show(inview: UIView) {
        let v = YiServerListView()
        
        v.frame = inview.bounds
        v.loadDatas()
        inview.addSubview(v)
    }
    
    private var selectedModel: YiServerListCellModel?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.registerCell()
        self.backgroundColor = .init(white: 0, alpha: 0.5)
        
        self.navView.leftBtn.img("arrow_51")
        self.navView.rightBtn.img("home_add")
        self.navView.titleL.text = "网络"
        
        self.loadDatas()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func loadDatas() {
//        var ar = [YiServerListCellModel]()
//        let nas = ["mackw", "liucc"]
//        for i in 0..<2 {
//            let m = YiServerListCellModel()
//            m.text = nas[i]
//            m.imgname = "home_pc"
//            ar.append(m)
//        }
//        self.datas = ar
        datas = DB.getServerList()
        self.tableView.reloadData()
    }
    
    // MARK: - TouchEvents
    override func handleNavRightBtn() {
        let typeList = YiTypeListView()
        self.currCtrl()?.addListView(typeList)
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        print(indexPath.row)
        
        self.searchSmbServer()
        return;
        
        if let m = self.model(datas, indexPath) as? YiServerListCellModel {
            
            selectedModel = m
            self.connectSmbServer(m)
        }
    }
    
    // MARK: - SMB
    func connectSmbServer(_ model: YiServerListCellModel) {
        if let host = model.ip {
            let name = model.text ?? host
            let fileServer = SMBFileServer.init(host: host, netbiosName: name, group: "WORKGROUP")
            
            fileServer?.connect(asUser: model.username, password: model.pwd, completion: { isguest, err in
                if let error = err {
                    print("Unable to connect: %@", error);
                } else if (isguest) {
                    print("Logged in as guest");
                } else {
                    print("Logged in success");
                    
                    self.listAllShares(fileServer: fileServer)
                }
            })

        }else {
            self.currCtrl()?.showErrorMsg("服务器ip错误")
        }
    }
    
    func listAllShares(fileServer: SMBFileServer?) {
        fileServer?.listShares { shares, error in
            if let err = error {
                print("Unable to list the shares: %@", err);
            }else{
                if let shares = shares {
                    //SMBShare
                    for share in shares {
                        print("Got share: %@", share.name);
                        if share.name == "cgw" {
                            
                            share.open { err in
                                if let error = err {
                                    print("Unable to open share: %@", error);
                                }else{
                                    
                                    print("Opened share '%@'", share.name);
                                    let root = SMBFile.root(of: share)
                                    self.listFiles(file: root)
                                }
                            }
                            break
                        }
                    }
                }
            }
        }
    }
    
    func listFiles(file:SMBFile?) {
        file?.listFiles({ files, error in
            if let error = error {
                print("Unable to list files: %@", error);
            } else if let files = files{
                print("Found %d files", files.count);
                
                let v = YiFileListView()
                v.serverModel = self.selectedModel
                v.loadDatas(datas: files, filedir: file)
                self.currCtrl()?.addListView(v)
            }
        })
    }
    
    func searchSmbServer() {
        
        SMBDiscovery.sharedInstance()?.start(of: .any, added: { smbDevice in
            print("Device added: %@", smbDevice);
            
            SMBDiscovery.sharedInstance()?.stop()
            
            let fileServer = smbDevice as? SMBFileServer
            
            fileServer?.connect(asUser: "wkun", password: "1212", completion: { isguest, err in
                if let error = err {
                    print("Unable to connect: %@", error);
                } else if (isguest) {
                    print("Logged in as guest");
                } else {
                    print("Logged in success");
                    
                    self.listAllShares(fileServer: fileServer)
                }
            })

            
        }, removed: { smbDevice in
            print("Device added: %@", smbDevice);
        })
    }

}

class YiServerListCellModel: YiListViewCellModel{
    var ip: String?
    var username: String?
    var pwd: String?
    var type: ServerType?
    var path: String?    //路径 暂无用
    var serverId: String? //对应数据库中的id
    var note: String? //备注
}
